package zzl.c._023;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author: zhangzeli
 * @date 10:09 2018/5/22
 * <P>测试schedule</P>
 */
public class Executor3 {
    public static void main(String[] args) {
//        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
//        //for (int i = 0; i < 10; i++) {
//            scheduledExecutorService.schedule(() -> {
//                while (true) {
//                    try {
//                        System.out.println(System.currentTimeMillis()/1000 + ":Thread Id=" + Thread.currentThread().getId());
//                        Thread.sleep(1000);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
//                }
//            }, 3L, TimeUnit.SECONDS);
        //}
        //test3();
        test4();
    }

    /**
     * 测试scheduleWithFixedDelay
     */
    public static void test3() {
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(10);
        //for (int i = 0; i < 10; i++) {
        scheduledExecutorService.scheduleWithFixedDelay(() -> {
            try {
                System.out.println(System.currentTimeMillis()/1000 + ":Thread Id=" + Thread.currentThread().getId());
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, 0L,2L, TimeUnit.SECONDS);
        //}
    }

    /**
     * 测试scheduleWithFixedDelay
     */
    public static void test4() {
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(2);
        //for (int i = 0; i < 10; i++) {
        scheduledExecutorService.scheduleAtFixedRate(() -> {
            try {
                System.out.println(System.currentTimeMillis()/1000 + ":Thread Id=" + Thread.currentThread().getId());
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, 0L,2L, TimeUnit.SECONDS);
        //}
    }
}
